//避免变量冲突和污染
;
(function () {

    $(function () {
        $.idcode.setCode(); //加载生成验证码方法

        //定义自己的规则
        $.validator.addMethod("checkPhone", (value, element, param) => {
            var reg = /^[1][3-9]\d{9}$/i;
            return reg.test(value);
        })

        $.validator.addMethod("checkPwd", (value, element, param) => {
            var reg = /^\w{6,12}$/i;
            return reg.test(value);
        })

        //给表单绑定事件
        $("form").validate({
            //规则
            rules: {
                uphone: {
                    required: true, //必填
                    checkPhone: true
                },
                upwd: {
                    required: true, //必填
                    rangelength: [6, 16],
                },
                agree: {
                    required: true
                }
            },
            //提示
            messages: {
                uphone: {
                    required: '手机号码必填',
                    checkPhone: "手机号码不合法"
                },
                upwd: {
                    required: '密码必填',
                    rangelength: "密码必须是{0}-{1}英文数字或者下划线",
                    checkPwd: "密码不合法"
                },
                agree: {
                    required: "必填项"
                }

            },
            //提交
            submitHandler: function () {
                var IsBy = $.idcode.validateCode();

                if (!IsBy) {

                    layer.msg('验证码错误!');
                    return false;
                } else {

                    //校验都通过,注册到cookie

                    var obj = {
                        uphone: $('[name="uphone"]').val(),
                        upwd: $('[name="upwd"]').val(),
                    }

                    //1.先读取cookie,转换成数组
                    var userList = JSON.parse($.cookie("users") || '[]');
                    //2.变量数组 判断是否已经注册
                    var flag = userList.some((el) => el.uphone == obj.uphone)
                    //3.如果没有注册,就保存到数组里
                    if (flag == true) {

                        layer.alert('手机号已注册!');
                        return false;
                    }
                    //4.把数组保存到cookie
                    userList.push(obj);
                    $.cookie.raw = true; //设置不使用编码
                    $.cookie("users", JSON.stringify(userList), {
                        expires: 10
                    });
                    //注册成功,是否理解去登录
                    layer.msg('玩命提示中')
                    layer.confirm("注册成功,是否立即去登录?", {
                        // skin: 'layui-layer-hei',
                        type: 1,
                        btn: ["Go", "Wait"]
                    }, (index) => {
                        layer.close(index);
                        window.location = "login.html"


                    }, () => { })


                }

                return false;
            }
        })





    });
})();